# coding:utf8

from appserver import db_store
from sqlalchemy.orm import relationship, backref
from sqlalchemy.sql import func,or_
from models.entity.model_base import ModelBase

from models.entity.device import Device

"""
设备类型分组
"""


class DeviceGroup(ModelBase):
    __tablename__ = "device_groups"
    __main__ = "main"

    # autoincrement=True,
    id = db_store.Column(db_store.Integer, primary_key=True, comment=u'主键')
    name = db_store.Column(db_store.String(64), nullable=False, unique=True, comment=u'分类名称')
    code = db_store.Column(db_store.String(36), nullable=False, unique=True, comment=u"分类编码")
    description = db_store.Column(db_store.String(255), nullable=False, comment=u"说明")
    icon=db_store.Column(db_store.String(32),comment=u"图标")

    def __repr__(self):
        return "<DeviceType %s>" % self.name

    
    def get_dic(self):
        rdic={}
        rdic["id"]=self.id
        rdic["name"]=self.name
        rdic["code"]=self.code
        rdic["icon"]=self.icon
        rdic["description"]=self.description
        device_num=len(Device.query.filter_by(device_group_id=self.id).all())
        rdic["device_num"]=device_num
        return rdic

    @staticmethod
    def get_device_group_by_id(id_num):
        return DeviceGroup.query.filter_by(id=id_num).first()

    @staticmethod
    def get_device_group_by_name(name):
        return DeviceGroup.query.filter_by(name=name).first()

    @staticmethod
    def get_device_group_by_code(code):
        return DeviceGroup.query.filter_by(code=code).first()

    @staticmethod
    def get_device_group_all():
        return DeviceGroup.query.all()
    
    @staticmethod
    def search(query_word):
        data = []
        groups = DeviceGroup.query.filter(
            or_(DeviceGroup.code.like('%' + query_word + '%'), DeviceGroup.name.like('%' + query_word + '%'),
                DeviceGroup.description.like('%' + query_word + '%'))).all()
        for obj in groups:
            data.append(obj.to_dict())
        return data
